<template>
  <div v-loading="isLoading">
    <div v-if="areaData.areaList.length === 0">
      <el-empty description="暂无数据" />
      <el-button @click="showArea('add')" style="margin-left: calc(50% - 50px)">+ 新增场地</el-button>
    </div>
    <div class="area" v-else>
      <div class="left content">
        <div v-for="item in areaData.areaList" :key="item.venueId" class="area-item" :class="areaData.currentAreaData.venueId === item.venueId
    ? 'active-area-item'
    : ''
    " @click="changeArea(item.venueId)">
          {{ item.venueName }}
        </div>
        <div class="area-add" @click="showArea('add')">+ 新增场地</div>
      </div>
      <div class="right content">
        <div class="right-header">
          <div class="flex-row-center" style="justify-content: space-between">
            <div class="flex-row-center">
              <h3 style="margin-right: 10px">
                {{ areaData.currentAreaData.venueName }}
              </h3>
              <el-tag class="ml-2" :type="status.tagType">{{
    status.tagText
  }}</el-tag>
            </div>
            <div class="flex-row-center">
              <el-switch v-model="areaData.currentAreaData.venueStatus" size="small" active-value="Y" inactive-value="N"
                @change="changeAreaStatus" />
              <el-icon :size="18" style="margin-left: 8px; cursor: pointer" @click="showArea('edit')">
                <Edit />
              </el-icon>
              <el-icon :size="18" style="margin-left: 8px; cursor: pointer" @click="deleteArea">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div class="address">{{ areaData.currentAreaData.venueAddress }}</div>
        </div>
        <el-tabs v-model="activeName" class="demo-tabs" type="border-card">
          <el-tab-pane label="场地信息" name="first">
            <BaseInfo :content="areaData.currentAreaData" @submitChange="getAreaDate" />
          </el-tab-pane>
          <el-tab-pane label="价格信息" name="second">
            <div v-for="(item, index) in state.list" :key="index" class="price-item">
              <el-checkbox v-model="item.openStatus" :value="item.dayOfWeek" true-value="Y" false-value="N"/>
              <div class="demo-time-range">
                <el-time-select v-model="item.startTime" :max-time="item.endTime" :clearable="false" start="08:00"
                  step="01:00" end="23:00" />
                -
                <el-time-select v-model="item.endTime" :min-time="item.startTime" :clearable="false" start="08:00"
                  step="01:00" end="23:00" />
              </div>
              <el-button link type="primary" @click="setPriceRange(index)">分段价格设置</el-button>
            </div>
            <div style="margin-top: 20px">
              <el-button type="primary" @click="handleSavePrice">保存</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <PriceRange ref="priceRangeRef" :currentIndex="state.currentIndex" :currentRow="state.list[state.currentIndex]"
      :change-price-range="changePriceRange" />
    <!-- 新增&编辑场地 -->
    <el-dialog v-model="dialogState.dialogVisible" :title="dialogTitle" width="40%">
      <el-form :model="dialogState.form" ref="formRef" label-width="120px">
        <el-form-item prop="venueName" label="场地名称：" :rules="[
    {
      required: true,
      message: '请输入场地名称',
      trigger: 'blur',
    },
  ]">
          <el-input v-model="dialogState.form.venueName" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="venueAddress" label="场地地址：" :rules="[
    {
      required: true,
      message: '请输入场地地址',
      trigger: 'blur',
    },
  ]">
          <el-input v-model="dialogState.form.venueAddress" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="venueType" label="场地类型：" :rules="[
    {
      required: true,
      message: '请选择场地类型',
      trigger: 'change',
    },
  ]">
          <el-radio-group v-model="dialogState.form.venueType">
            <el-radio label="football">足球</el-radio>
            <el-radio label="baseball">棒球</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel(formRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { computed, reactive, ref } from "vue";
import BaseInfo from "./Components/BaseInfo.vue";
import PriceRange from "./Components/PriceRange.vue";
import {
  getAreaList,
  postAddArea,
  postUpdateArea,
  postDelArea,
} from "@/api/area/index.ts"

// 场馆信息
interface AreaInfoEnum {
  venueId?: Number; // 场馆id
  venueName: string; //场馆名称
  venueAddress: string; //场馆地址
  venueStatus: string; //场馆状态
  venueType: string; //场馆类型
  venueInfo: string; //场馆介绍
  venuePhoto: string; //场馆图
  venueAlbum: string[]; //场地分布图
  venueSiteList: AreaSiteEnum[]; //场地信息
  venuePriceList: AreaPriceEnum[]; //价格信息
  venueMinOrderHours: number; //最小预约时间
  venueBusinessHours: string; //营业时间
  venueTag: string[]; //标签
}
interface AreaSiteEnum {
  siteName: string; //场地名
  siteType: string; //场地类型
}
interface AreaPriceEnum {
  dayOfWeek: string; //周几
  opneStatus: string; //开放状态
  startTime: string; //开始时间
  endTime: string; //结束时间
  fullPrice: Number; //全场价格
  halfPrice: Number; //半场价格
}

const isLoading = ref(false);
// 场馆信息
const areaData = reactive({
  areaList: ref<AreaInfoEnum[]>([]),
  currentAreaData: ref<AreaInfoEnum>({}),
});
// 场馆状态计算属性 number->boolean
const status = computed(() => {
  return {
    checked: areaData.currentAreaData.venueStatus === "Y" ? true : false,
    tagType:
      areaData.currentAreaData.venueStatus === "Y" ? "success" : "danger",
    tagText: areaData.currentAreaData.venueStatus === "Y" ? "开馆" : "闭馆",
  };
});
const activeName = ref("first");
const priceRangeRef = ref();
const state = reactive({
  currentIndex: 0, // 当前设置的是第几周，0为批量设置的
  list: [
    {
      openStatus: "N",
      dayOfWeek: "周一",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周二",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周三",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周四",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周五",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周六",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周日",
      startTime: "",
      endTime: "",
      priceData: [],
    },
  ],
});

// 切换场馆
const changeArea = (uuid: Number | undefined) => {
  areaData.currentAreaData = areaData.areaList.find(
    (i) => i.venueId === uuid
  ) as any; // @todo-类型
  initDate();
};
// 修改场馆状态
const changeAreaStatus = () => {
  postUpdateArea(areaData.currentAreaData);
};
// 删除场馆
const deleteArea = () => {
  ElMessageBox.confirm("确认要删除该场地吗？删除后将无法恢复！", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // @todo-删除掉接口
    postDelArea({
      venueId: areaData.currentAreaData.venueId,
    }).then(() => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      // 更新数据
      getAreaDate();
    });
  });
};

const formRef = ref();
const dialogState = reactive({
  dialogVisible: false,
  type: "add",
  form: {
    venueName: "",
    venueAddress: "",
    venueType: "football",
    venueStatus: "Y",
  },
});
// 对话框标题
const dialogTitle = computed(() => {
  return dialogState.type === "add" ? "新增场地" : "编辑场地";
});
// 新增/编辑场地
const showArea = (type: string) => {
  (dialogState.dialogVisible = true), (dialogState.type = type);
  if (type === "edit") {
    dialogState.form = { ...areaData.currentAreaData };
  } else {
    dialogState.form = {
      venueName: "",
      venueAddress: "",
      venueType: "football",
      venueStatus: "Y",
    }
  }
};
const handleCancel = (formEl: FormInstance | undefined) => {
  dialogState.dialogVisible = false;
  if (!formEl) return;
  formEl.resetFields();
};
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (dialogState.type === "edit") {
        postUpdateArea(dialogState.form).then(() => {
          // 更新数据
          getAreaDate();
        });
      } else {
        const newItem = {
          venueId: Number(areaData.areaList.length + 1),
          venueName: dialogState.form.venueName,
          venueAddress: dialogState.form.venueAddress,
          venueStatus: dialogState.form.venueStatus,
          venueType: dialogState.form.venueType,
          venueInfo: "", //场馆介绍
          venuePhoto: "", //场馆图
          venueAlbum: [], //场地分布图
          venueSiteList: [], //场地信息
          venuePriceList: [], //价格信息
          venueMinOrderHours: 2, // 最小预约时间
          venueBusinessHours: "", // 营业时间
          venueTag: [], //标签
        };
        areaData.areaList.push(newItem);
        areaData.currentAreaData = newItem;
        postAddArea(dialogState.form).then(() => {
          // 更新数据
          getAreaDate();
        });
      }
      dialogState.dialogVisible = false;
      formEl.resetFields();
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
// 价格设置
const initDate = () => {
  let len = Number(areaData.currentAreaData.venuePriceList.length);
  state.list = [
    {
      openStatus: "N",
      dayOfWeek: "周一",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周二",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周三",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周四",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周五",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周六",
      startTime: "",
      endTime: "",
      priceData: [],
    },
    {
      openStatus: "N",
      dayOfWeek: "周日",
      startTime: "",
      endTime: "",
      priceData: [],
    },
  ];
  if (len > 0) {
    areaData.currentAreaData.venuePriceList.map((item: any) => {
      switch (item.dayOfWeek) {
        case (item.dayOfWeek = "周一"):
          state.list[0].openStatus = item.openStatus;
          state.list[0].priceData.push(item);
          break;
        case (item.dayOfWeek = "周二"):
          state.list[1].openStatus = item.openStatus;
          state.list[1].priceData.push(item);
          break;
        case (item.dayOfWeek = "周三"):
          state.list[2].openStatus = item.openStatus;
          state.list[2].priceData.push(item);
          break;
        case (item.dayOfWeek = "周四"):
          state.list[3].openStatus = item.openStatus;
          state.list[3].priceData.push(item);
          break;
        case (item.dayOfWeek = "周五"):
          state.list[4].openStatus = item.openStatus;
          state.list[4].priceData.push(item);
          break;
        case (item.dayOfWeek = "周六"):
          state.list[5].openStatus = item.openStatus;
          state.list[5].priceData.push(item);
          break;
        case (item.dayOfWeek = "周日"):
          state.list[6].openStatus = item.openStatus;
          state.list[6].priceData.push(item);
          break;
      }
    });
    state.list.map((item) => {
      item.startTime = item.priceData.length > 0 ? item.priceData[0].startTime : "";
      item.endTime = item.priceData.length > 0 ? item.priceData[item.priceData.length - 1].endTime : "";
    })
  } else {
    state.list.map((item) => {
      item.openStatus = "N";
      item.startTime = "";
      item.endTime = "";
      item.priceData = [];
    });
  }
};
const setPriceRange = (index: number, isSet = true) => {
  const { startTime, endTime, priceData } = state.list[index];
  if (!startTime || !endTime) {
    ElMessage({
      message: "请填写开放时间",
      type: "warning",
    });
    return;
  }
  const curStartTime = priceData.length ? Number(priceData[0].startTime.split(":")[0]) : 0
  const curEndTime = priceData.length ? Number(priceData[priceData.length - 1].endTime.split(":")[0]) : 0
  if (priceData.length === 0 || curStartTime != Number(startTime.split(":")[0]) || curEndTime != Number(endTime.split(":")[0])) {
    // 设置默认的时间价格
    const hours =
      Number(endTime.split(":")[0]) - Number(startTime.split(":")[0]);
    const _priceData: any = [];
    for (let i = 0; i < hours; i++) {
      const _startTime = Number(startTime.split(":")[0]) + i;
      const _startTimeStr =
        _startTime.toString().length < 2
          ? "0" + _startTime.toString()
          : _startTime.toString();
      const _endTimeStr =
        (Number(startTime.split(":")[0]) + i + 1).toString().length < 2
          ? "0" + (Number(startTime.split(":")[0]) + i + 1).toString()
          : (Number(startTime.split(":")[0]) + i + 1).toString();
      const item = {
        openStatus: state.list[index].openStatus,
        dayOfWeek: state.list[index].dayOfWeek,
        startTime: _startTimeStr + ":00",
        endTime: _endTimeStr + ":00",
        fullPrice: 1200,
      };
      _priceData.push(item);
    }
    state.list[index].priceData = _priceData;
  }
  state.currentIndex = index;
  isSet? priceRangeRef.value.dialogVisible = true: '';
};

const changePriceRange = (index: number, row: any, isSet = true) => {
  state.list[index].priceData = row.priceData;
  let arr: any = [];
  state.list.map((item) => {
    if (item.priceData.length > 0) {
      item.priceData.map((t: any) => {
        t.openStatus = item.openStatus;
        arr.push(t);
      });
    }
  });
  areaData.currentAreaData.venuePriceList = arr;
  isSet? handleChangePrice() : ''
};

const handleSavePrice = ()=> {
  state.list.forEach((item: any,index: number)=> {
    if (item.startTime || item.endTime) {
      setPriceRange(index, false)
      changePriceRange(index, item, false)
    }
  })
  handleChangePrice()
}
const handleChangePrice = () => {
  postUpdateArea(areaData.currentAreaData).then(() => {
    ElMessage({
      message: "保存成功",
      type: "success",
    });
    initDate()
  });
};
// 查询场地信息
const getAreaDate = () => {
  isLoading.value = true;
  getAreaList().then((res) => {
    areaData.areaList = res.data || [];
    if (Object.keys(areaData.currentAreaData).length > 0 && res.data.length > 0) {
      res.data.map((item: AreaInfoEnum) => {
        if (areaData.currentAreaData.venueName === item.venueName) {
          areaData.currentAreaData = item
        }
      })
    } else if (res.data.length > 0) {
      areaData.currentAreaData = res.data[0];
      initDate()
    }
    isLoading.value = false;
  });
};
getAreaDate();
</script>

<style lang="scss" scoped>
.area {
  display: flex;
  flex-direction: row;
  background: #fff;
  height: calc(100vh - 60px - 30px);

  .left {
    width: 160px;
    border-right: 0.5px solid #eeeeee;

    .area-item {
      padding: 10px;
      border-radius: 2px;
      cursor: pointer;
    }

    .active-area-item {
      background-color: #d9ecff;
      border-left: 3px solid #9acaf9;
    }

    .area-add {
      padding: 10px;
      cursor: pointer;
    }
  }

  .right {
    width: 100%;

    .flex-row-center {
      display: flex;
      align-items: center;
    }

    .right-header {
      border-bottom: 1px solid #eeeeee;
      padding: 10px;

      .address {
        color: #676666;
        margin: 15px 0 0 0;
      }
    }

    .price-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .demo-time-range {
        margin-left: 15px;
        margin-right: 15px;
      }
    }
  }
}
</style>